<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <basic-container>
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane
          label="当月缴纳"
          name="first"
        ></el-tab-pane>
        <el-tab-pane
          label="已缴纳"
          name="second"
        ></el-tab-pane>
        <el-tab-pane
          label="未缴纳"
          name="fourth"
        ></el-tab-pane>
        <el-tab-pane
          label="欠费"
          name="third"
        ></el-tab-pane>
      </el-tabs>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :search.sync="searchForm"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
        @search-reset="resetChange"
        @selection-change="selectionChange"
      >
        <template slot="menuLeft">
          <el-button
            type="primary"
            icon="el-icon-notebook-2"
            v-if="activeName!='second' || activeName=='third'"
            @click="pays"
          >
            合并缴费
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-tickets"
            v-if="activeName=='second' || activeName=='third'"
            @click="invoice"
          >
            合并开票
          </el-button>
        </template>
        <template
          slot-scope="scope"
          slot="monthSearch"
        >
          <el-input
            placeholder="欠费月份"
            v-model="searchForm.month"
            @input.native="searchForm.month = test(searchForm.month)"
            @blur.native="searchForm.month = test(searchForm.month)"
          ></el-input>
        </template>
        <template
          slot="buildingType"
          slot-scope="scope"
        >
          {{scope.row.buildingType | getBuildingType(that)}}
        </template>
        <template
          slot-scope="scope"
          slot="buildingTypeSearch"
        >
          <!-- <el-input placeholder="自定义输入框"  v-model="scope.row.buildingType"></el-input> -->
          <el-select
            v-model="searchForm.buildingType"
            clearable
            placeholder="选择房产类型"
          >
            <el-option
              v-for="(item,index) in buidingOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>

        <template slot="searchMenu">
          <el-button
            size="small"
            icon="el-icon-download"
            @click="exportExcel"
          >导出</el-button>
        </template>
        <template
          slot-scope="scope"
          slot="menu"
        >
          <el-button
            :type="'text'"
            v-if='scope.row.isPayment!=1'
            @click="pay(scope.row)"
          >缴费</el-button>
          <el-button
            :type="'text'"
            @click="detail(scope.row.id)"
          >明细</el-button>

          <el-button
            :type="'text'"
            @click="payrecroed(scope.row)"
          >缴费记录</el-button>
        </template>
      </avue-crud>
      <pay
        ref="pay"
        @refreshList='refreshList'
      ></pay>
      <detail ref="detail"></detail>
      <payrecroed ref="payrecroed"></payrecroed>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj } from '@/api/mrcost'
import { tableOption } from '@/const/crud/mrcost'
import { mapGetters } from 'vuex'
import { getDicType, ExportFile } from '@/api/common'
import pay from '@/components/invoice/pay'
import detail from './detail'
import payrecroed from './payrecroed'
export default {
  name: 'mrcost',
  components: { pay, detail, payrecroed },
  data () {
    return {
      activeName: 'first',
      searchForm: {
        buildingType: '',
        isPayment: 3,
        month: ''
      },
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      buidingOptions: [],
      that: this,
      selectList: []
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList () {
      return {
        addBtn: this.vaildData(this.permissions.generator_mrcost_add, false),
        delBtn: this.vaildData(this.permissions.generator_mrcost_del, false),
        editBtn: this.vaildData(this.permissions.generator_mrcost_edit, false)
      };
    }
  },
  mounted () {
    getDicType('rm_project_buiding_type').then(res => {
      this.buidingOptions = res.data.data
    })
  },
  filters: {
    getBuildingType (value, that) {
      let str = ''
      that.buidingOptions.forEach(item => {
        if (value == item.value) {
          str = item.label
        }
      })
      return str
    }
  },
  methods: {
    exportExcel () {
      ExportFile('/cost/mrcost/export', this.searchForm)
    },
    test (value) {
      return value.replace(/[^0-9]/g, '')
    },
    // 切换状态
    handleClick (tab, event) {
      if (this.activeName == 'first') {
        this.searchForm.isPayment = 3
        this.tableOption.column[9].search = false
      } else if (this.activeName == 'second') {
        this.tableOption.column[9].search = false
        this.searchForm.isPayment = 1
      } else if (this.activeName == 'third') {
        this.searchForm.isPayment = 2
        this.tableOption.column[9].search = true
      } else if (this.activeName == 'fourth') {
        this.searchForm.isPayment = 0
        this.tableOption.column[9].search = false
      }
      this.getList()
    },
    // 缴纳记录
    payrecroed (id) {
      this.$refs.payrecroed.init(id.projectId)
    },
    detail (id) {
      this.$refs.detail.init(id)
    },
    pay (item) {
      this.$refs.pay.init([item], 2)
    },
    refreshList () {
      this.getList()
    },
    getList (page, params) {
      this.tableLoading = true
      fetchList(Object.assign({
        current: this.page.currentPage,
        size: this.page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    rowDel: function (row, index) {
      this.$confirm('是否确认删除此条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    handleUpdate: function (row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading();
      });
    },
    handleSave: function (row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading();
      });
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange (current) {
      this.page.currentPage = current
    },
    searchChange (form, done) {
      // this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    refreshChange () {
      this.getList(this.page)
    },
    resetChange () {
      this.searchForm.buildingType = ''
      this.searchForm.month = ''
    },
    selectionChange (list) {
      this.selectList = []
      this.selectList = list
    },
    isIdentical (type) {
      let flag = true
      let idList = []
      this.selectList.some((item, index) => {
        if (idList.includes(item.companyId)) {
        } else {
          idList.push(item.companyId)
        }
        if (idList.length >= 2) {
          flag = false
          return true
        }
      })
      if (!flag) {
        let name = type ? '缴费' : '开票'
        let title = type ? '缴费提示' : '开票提示'
        this.$alert('<div>当前选中的公司不一致，无法进行' + name + '操作</div>', title, {
          dangerouslyUseHTMLString: true
        });
      }
      return flag
    },
    pays () {
      if (this.selectList.length >= 2 && !this.isIdentical(1)) {
        return
      }
      let IsPay = true
      let indexList = []
      this.selectList.forEach((item, index) => {
        if (item.isPayment == 1) {
          IsPay = false
          indexList.push(item.$index + 1)
        }
      })
      if (IsPay) {
        this.$refs.pay.init(this.selectList, 2)
      } else {
        this.$alert('<div>以下数据序号存在已缴费</div><div>序号分别为<span style=\'font-size:18px;font-weight: bold;\'>[' + indexList + ']</span></div>', '缴费提示', {
          dangerouslyUseHTMLString: true
        });
      }
    },
    invoice () {
      if (this.selectList.length >= 2 && !this.isIdentical(0)) {
        return
      }
      let IsPay = true
      let indexList = []
      this.selectList.forEach((item, index) => {
        if (item.isPayment == 0 || item.isInvoice == 0) {
          IsPay = false
          indexList.push(item.$index + 1)
        }
      })
      if (IsPay) {
        this.$refs.pay.init(this.selectList, 2, null, 1)
      } else {
        this.$alert('<div>勾选数据中存在未缴费或已开票的数据</div><div>序号分别为<span style=\'font-size:18px;font-weight: bold;\'>[' + indexList + ']</span></div>', '开票提示', {
          dangerouslyUseHTMLString: true
        });
      }
    }
  }
}
</script>
